package cn.iocoder.yudao.module.chat.controller.app.gpt;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.websocket.core.WebSocketUser;
import cn.iocoder.yudao.module.chat.ErrorCodeConstants;
import cn.iocoder.yudao.module.chat.controller.app.gpt.vo.ChatMessageVO;
import cn.iocoder.yudao.module.chat.service.gpt.ChatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
@Slf4j
@RequestMapping("/chat/gpt")
@RestController
public class AppChatGPTController {


    @Resource
    private ChatService chatService;
    @MessageMapping("/ask")
    @SendTo("/chatgpt/question")
    public CommonResult<ChatMessageVO> gptAsk(@RequestBody ChatMessageVO message) {
        return success(message);
    }
    @MessageMapping("/userAsk")
    @OperateLog(enable = false) // 避免每次websocket请求被记录操作日志
    public void gptUserAsk(@RequestBody ChatMessageVO message, WebSocketUser authentication) {
        message.setUserId(authentication.getId());
        message.setSessionId(authentication.getSessionId());
        message.setTenantId(authentication.getTenantId());
        if(ObjectUtil.isNull(authentication)){
            return;
        }
        chatService.executeChat(message);
    }

    @GetMapping("/registerChat")
    public CommonResult<String> registerChat(){
        String s = chatService.registerChatSession();
        if(StrUtil.isEmpty(s)){
            CommonResult.error(ErrorCodeConstants.OPENAI_CHAT_REQUEST_FAILURE);
        }
        return CommonResult.success("success");
    }

}
